from config import *
from winLogin import WinLogin
from winChat import WinChat
from clientSocket import ClientSocket
from requestProtocol import RequestProtocol
from tkinter.messagebox import *
from threading import Thread


class Client():
    def __init__(self):
        self.window_init()

    def window_init(self):
        self.client_socket = ClientSocket() #client套接字
        self.window = WinLogin()    #登录窗口
        self.window.on_button_login_click(self.login)
        self.window.bind("<Return>",self.return_login)
        self.window.on_window_closed(self.close_window)

        self.winChat = WinChat()    #聊天窗口
        self.winChat.withdraw()
        self.winChat.on_send_button_click(self.send_message)
        self.winChat.bind("<Return>",self.return_send_message)
        self.winChat.on_window_closed(self.close_window)
    def run(self):
        self.client_socket.connect()
        Thread(target=self.response_handle).start()

        self.window.mainloop()
    #登录业务流程
    def login(self):
        #1.获取账号和密码
        username = self.window.get_username()
        password = self.window.get_pwd()
        #2.将账号和密码打包
        request_login = RequestProtocol.request_login_result(username,password)
        self.client_socket.send_data(request_login)

    #登录业务流程
    def return_login(self,event):
        #1.获取账号和密码
        username = self.window.get_username()
        password = self.window.get_pwd()
        #2.将账号和密码打包
        request_login = RequestProtocol.request_login_result(username,password)
        self.client_socket.send_data(request_login)

    #对服务器发送的信息进行相应，用子线程来处理
    def response_handle(self):
        #注册线程处理函数
        handle_func = dict()
        handle_func[RESPONSE_LONGI_RESULT] = self.response_login_handle
        handle_func[RESPONSE_CHAT] = self.response_chat_handle
        handle_func[RESPONSE_UPDATE_ONLINE] = self.response_update_onlineusers_handle
        while True:
            # 接收和分析服务器的响应信息
            response = self.client_socket.recv_data()
            print(response)
            response_data = self.parse_response(response)
            response_id = response_data['response_id']
            handle_func[response_id](response_data)

    #登陆响应处理
    def response_login_handle(self,response_data):
        # 失败则显示登陆出错，重新发送信息
        if response_data['result'] == '0':
            showinfo(title='登陆失败', message=response_data['nickname'])
        # 成功则进入聊天界面
        elif response_data['result'] == '1':
            showinfo(title='登陆成功', message='进入聊天室')
            self.user_info = response_data
            self.window.withdraw()
            self.winChat.deiconify()
            response_data['onlineusers']
            self.winChat.update_onlineusers(response_data['onlineusers'])

    #聊天信息响应处理
    def response_chat_handle(self,response_data):
        sender = response_data['nickname']
        messages = response_data['messages']
        self.winChat.append_message(sender,messages)

    def response_update_onlineusers_handle(self,response_data):
        self.winChat.update_onlineusers(response_data['onlineusers'])

    # 解析相应信息，登录响应格式：1001|ret|nickname|username|onlinename，聊天响应格式：1002|nickname|messages
    def parse_response(self,response):
        response_list = response.split('|')
        response_data = dict()
        if response_list[0] == RESPONSE_LONGI_RESULT:
            response_data['response_id'] = response_list[0]
            response_data['result'] = response_list[1]
            response_data['nickname'] = response_list[2]
            response_data['username'] = response_list[3]
            response_data['onlineusers'] = response_list[4]
        elif response_list[0] == RESPONSE_CHAT:
            response_data['response_id'] = response_list[0]
            response_data['nickname'] = response_list[1]
            response_data['messages'] = response_list[2]
        elif response_list[0] == RESPONSE_UPDATE_ONLINE:
            response_data['response_id'] = response_list[0]
            response_data['onlineusers'] = response_list[1]
        return response_data

    #在聊天室发送信息
    def send_message(self):
        #获取输入框的内容
        message = self.winChat.get_inputs()
        self.winChat.clear_inputs()
        #打包发给服务器
        message_to_send = RequestProtocol.response_chat(self.user_info['nickname'],message)
        self.client_socket.send_data(message_to_send)

    #在聊天室发送信息
    def return_send_message(self,event):
        #获取输入框的内容
        message = self.winChat.get_inputs()
        self.winChat.clear_inputs()
        #打包发给服务器
        message_to_send = RequestProtocol.response_chat(self.user_info['nickname'],message)
        self.client_socket.send_data(message_to_send)
    def close_window(self):
        self.client_socket.close()
        exit()

if __name__ == '__main__':
    client = Client()
    client.run()